package com.hjy.demo.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.apache.shiro.mgt.SecurityManager;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //注入 redis 参数
     @Value("${spring.redis.host}")
     private String host;
     @Value("${spring.redis.port}")
     private int port;
     @Value("${spring.redis.password}")
     private String password;
     @Value("${spring.redis.timeout}")
     private int timeout;

    //1.自定义的Realm
    @Bean(name = "realm")
    public MyShiroRealm myShiroRealm(){
        MyShiroRealm myShiroRealm =new MyShiroRealm();
        //告诉realm，使用credentialsMatcher加密算法类来验证密文
        myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        //启动缓存及设置缓存名称
        myShiroRealm.setCachingEnabled(true);
        myShiroRealm.setAuthorizationCachingEnabled(true);
        myShiroRealm.setAuthorizationCacheName("authorizationCache");
        return myShiroRealm;
    }

    //2.根据注入的realm创建一个安全管理器
    @Bean(name = "securityManager")
    public DefaultSecurityManager securityManager(@Qualifier("realm")Realm realm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //设置realm
        securityManager.setRealm(realm);
        return securityManager;
    }

    /**
     * 创建ShiroFilterFactoryBean
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager securityManager){
        System.out.println("ShiroConfiguration.shiroFilter():配置权限控制规则");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        Map<String,String> map = new LinkedHashMap<>();
        /**  32.
         *  常见过滤器：
         *  * anon：无需认证（登录）可以访问
         *  * authc：必须认证才可以访问
         *  * user:如果使用 Remember Me 的功能，可以直接访问
         *  * perms:该资源必须得到资源权限才可以访问
         *  * role:该资源必须得到角色权限才可以访问      */
        // 配置不会被拦截的链接 顺序判断
        map.put("/css/**", "anon");
        map.put("/fonts/**", "anon");
        map.put("/images/**", "anon");
        map.put("/js/**", "anon");
        map.put("/localcss/**", "anon");
        map.put("/dologin", "anon");

        //配置测试权限（真实权限应该从数据库中获得）
        map.put("/user/list", "perms[用户管理]");
        map.put("/user/add", "perms[用户添加]");
        map.put("/user/edit", "perms[用户编辑]");
        map.put("/role/list", "perms[角色管理]");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        shiroFilterFactoryBean.setLoginUrl("/login"); //设置登录页面
        shiroFilterFactoryBean.setSuccessUrl("/main");//登录成功跳转的页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");  //设置未授权时要显示的页面

        //必须设置 SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        return shiroFilterFactoryBean;
    }

    /**  * 配置 thymeleaf 页面对 shiro 标签的支持  */
    @Bean(name = "shiroDialect")
    public ShiroDialect shiroDialect() {
        return new ShiroDialect(); }

    /**
     *
    * 配置 shiro redisManager
     * * 使用的是 shiro-redis 开源插件
     * * @return        */
    public RedisManager redisManager() {
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(host);
        redisManager.setPort(port);
        redisManager.setPassword(password);
        redisManager.setTimeout(timeout);
        return redisManager;
    }
    /**   cacheManager 缓存 redis 实现
    * 使用的是 shiro-redis 开源插件
     * * @return       */
    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        //缓存名称
        redisCacheManager.setPrincipalIdFieldName("usrName");
        //缓存时间
              redisCacheManager.setExpire(1800);
              return redisCacheManager;
    }
    /**   RedisSessionDAO shiro sessionDao 层的实现 通过 redis
       使用的是 shiro-redis 开源插件  154.      */
    @Bean
    public RedisSessionDAO redisSessionDAO() {
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(redisManager());
        return redisSessionDAO;
    }
    /**  Session Manager
     * 使用的是 shiro-redis 开源插件
     */
    @Bean
    public DefaultWebSessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setSessionDAO(redisSessionDAO());
        return sessionManager;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        System.out.println("hashedCredentialsMatcher..........");
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //使用md5算法进行加密
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        //设置散列次数：意为加密几次
        hashedCredentialsMatcher.setHashIterations(1);
        return hashedCredentialsMatcher;
    }
}
